package com.ask.utils;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

public class MD5Util {

	private static final Logger LOG = LogManager.getLogger(MD5Util.class);

	/**
	 * 生成token的salt
	 */
	private static final String TOKEN_SALT = "fdas34ljfr灵sja@#8$%dfkl;js&4*daklf创jsdl";

	private static final char hexDigits[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e',
			'f' };

	public static void main(String[] args) {
		StringBuffer sb = new StringBuffer();
		sb.append("LCVWchannel:society&timestamp:1489736746.341488LCVW");
		System.out.println(System.currentTimeMillis() / 1000);
		System.out.println(getEncrypted("LCVWsearchWord:阶级&timestamp:1494570013258LCVW"));
	}

	/**
	 * 获得加密后的口令
	 *
	 * @param origin
	 *            原始串码
	 * @return 加密后的串码
	 */
	public static String getEncrypted(String origin) {
		byte[] strTemp = null;
		MessageDigest mdTemp = null;
		try {
			strTemp = origin.getBytes("utf-8");
			mdTemp = MessageDigest.getInstance("MD5");
		} catch (UnsupportedEncodingException e1) {
			LOG.error("get bytes failed, string={}", origin, e1);
			return null;
		} catch (NoSuchAlgorithmException e) {
			LOG.error("have no such Algorithm", e);
			return null;
		}
		mdTemp.update(strTemp);
		byte[] md = mdTemp.digest();
		int j = md.length;
		char str[] = new char[j * 2];
		int k = 0;
		for (int i = 0; i < j; i++) {
			byte byte0 = md[i];
			str[k++] = hexDigits[byte0 >>> 4 & 0xf];
			str[k++] = hexDigits[byte0 & 0xf];
		}
		String reuslt = new String(str);
		return reuslt;
	}

	/**
	 * 根据userId生成token
	 *
	 * @param userId
	 * @return
	 */
	public static String getToken(Long userId) {
		// 将用户Id，时间戳和accessKey拼接
		StringBuffer origin = new StringBuffer();
		origin.append(userId).append(System.currentTimeMillis()).append("app").append(TOKEN_SALT);
		// 将串码采用MD5加密
		String token = MD5Util.getEncrypted(origin.toString());
		return token;
	}

	/**
	 * WEB端根据userId生成token
	 *
	 * @param userId
	 * @return
	 */
	public static String getWebToken(Long userId) {
		// 将用户Id，时间戳和accessKey拼接
		StringBuffer origin = new StringBuffer();
		origin.append(userId).append(System.currentTimeMillis()).append("web").append(TOKEN_SALT);
		// 将串码采用MD5加密
		String token = MD5Util.getEncrypted(origin.toString());
		return token;
	}
}